package com.ia.bikerecife.communication;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.ia.bikerecife.MainActivity;
import com.ia.bikerecife.SettingsActivity;

public class TaskComunication extends AsyncTask<Void, Void, Void> {

    private String           mMessage;

    public ProgressDialog    mDialog;

    private Socket           socket;
    private DataOutputStream out;
    private DataInputStream  in;

    public TaskComunication(ProgressDialog dialog, String message) {
        mMessage = message;
        mDialog = dialog;
    }

    @Override
    protected void onPreExecute() {
        mDialog.show();
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            socket = new Socket(SettingsActivity.IP, SettingsActivity.PORT);
            out = new DataOutputStream(socket.getOutputStream());
            in = new DataInputStream(socket.getInputStream());
            out.writeUTF(mMessage);
            out.flush();
            MainActivity.mMessage = in.readUTF();
        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        mDialog.dismiss();
        try {
            if (out != null)
                out.close();
            if (in != null)
                in.close();
            if (socket != null)
                socket.close();
            mDialog.dismiss();

        }
        catch (IOException e) {
            // e.printStackTrace();
        }

    }
}
